import Service from '../../core/baseService';

export default class CollectService extends Service {
  constructor(ctx) {
    super(ctx);
    this.model = this.ctx.model.Collect;
  }

  async index(page = 1, pageSize = 20, query) {
    const result: any = await this.model
      .findAndCountAll({
        where: query,
        include: [{ model: this.ctx.model.Goods, }],
        offset: (Number(page) - 1) * pageSize,
        limit: pageSize,
        order: [['id', 'DESC']],
      });
    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize,
    }
  };

  async create(data) {
    const isExist = await this.model.findOne({
      where: data
    });
    let isCollect = false;
    if (isExist) {
      await this.model.destroy({ where: { id: isExist.id } });
      isCollect = false ;
    } else {
      await this.model.create(data);
      isCollect = true;
    }
    return isCollect;
  }


  async add(data) {
    const { goods_id, user_id, number } = data;

    const ans: any = await this.ctx.model.Collect.findOne({
      where: {
        goods_id,
        user_id
      }
    });

    let result: any = {}
    if (ans) {
      result = await this.ctx.model.Collect
        .update(
          {
            number: ans.number + number
          },
          { where: { id: ans.id } }
        )
    } else {
      result = await this.ctx.model.Collect.create(data);
    }
    return result;
  }


}
